<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <el-card class="house">
    <template #header>
      <div class="card-header">
        <span style="font-weight: 600; font-size: 18px;cursor: pointer;" @click="()=>{router.push('/')}">查看房户信息</span>
        <span style="font-weight: 600; font-size: 18px;cursor: pointer;" @click="()=>{router.push('/setBuild')}">/分层分户</span>
        <span style="font-weight: 600; font-size: 18px;cursor: pointer;" @click="()=>{router.push('/setInfo')}">/录入信息</span>
        <el-select
          v-model="data.pickBuild"
          placeholder="请选择楼栋"
          style="float: right; width: 230px"
          @change="changeBuild"
        >
          <el-option
            v-for="item in data.buildArr"
            :key="item.id"
            :label="item.name"
            :value="item"
          />
        </el-select>
      </div>
    </template>
  </el-card>
</template>
<script setup>
import { onMounted, getCurrentInstance, reactive, onUnmounted } from 'vue'
import * as Cesium from 'cesium'
import * as turf from '@turf/turf'
import { ElMessage } from 'element-plus'
import { getBuild } from '@/api/buildApi'
import { getHouse, getOneHouseInfo } from '@/api/houseApi'
import Bubble from '@/tool/bubble'
import { useRouter } from 'vue-router'
const router = useRouter()
// 全局变量
const { appContext } = getCurrentInstance()
const global = appContext.config.globalProperties
let viewer

// 响应数据
const data = reactive({
  buildArr: [],
  pickBuild: null,
  query: {
    noPage: 1
  }
})
// 颜色数组
const colors = [
  '#99CCCC',
  '#66FF66',
  '#FF6666',
  '#00CCFF',
  '#00FF33',
  '#CC00CC',
  '#CCFF00',
  '#0000FF',
  '#CC0000'
]

// 初始化下拉框选项数据
const initData = async () => {
  const res = await getBuild()
  if (res.code == 200) {
    ElMessage.success('数据请求成功')
  }
  data.buildArr = res.data
}

// 点击选项时,视角跳转、加载分层数据
let heightList = []
const changeBuild = (item) => {
  const center = turf.center(item.polygon)
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(...center.geometry.coordinates, 200)
  })
  // 加载分层数据
  data.query.id = item.id
  getHouseData()
  // 清除之前的高亮户
  heightList.length &&
    heightList.forEach((item) => {
      viewer.scene.primitives.remove(item)
    })
  heightList = []
}
// 获取这栋楼的每层数据并加载primitive的方法封装
const getHouseData = async () => {
  const res = await getHouse(data.query)
  console.log(res, '每户数据')
  if (res.code == 200) {
    res.data.forEach((item) => {
      let arr = item.polygon.coordinates[0].flat()
      // 新建紧贴3DTiles的primitive
      let height, extrudedHeight
      height = item.minHeight
      extrudedHeight = item.maxHeight
      let primitive = new Cesium.ClassificationPrimitive({
        geometryInstances: new Cesium.GeometryInstance({
          geometry: new Cesium.PolygonGeometry({
            polygonHierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(arr)),
            height,
            extrudedHeight
          }),
          id: item.id,
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(
              Cesium.Color.fromCssColorString(colors[item.id % 9]).withAlpha(0.3)
            )
          }
        }),
        classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
      })
      viewer.scene.primitives.add(primitive)
      heightList.push(primitive)
    })
  }
}

// 初始化点击事件
let handler, bubble,pickPrimitive
const initHandler = async () => {
  handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  handler.setInputAction(async (event) => {
    let pick = viewer.scene.pick(event.position)
    let position = viewer.scene.pickPosition(event.position)
    // 页面初始化时就激活了点击事件，为了避免误触，通过判断拾取的实体是否有 id值来确定是不是之前添加的 primitive
    if (position && pick && pick.id) {
      // 取消高亮图元
      if(pickPrimitive){
        console.log(pickPrimitive,pickPrimitive.primitive);
        let attributes = pickPrimitive.primitive.getGeometryInstanceAttributes(pickPrimitive.id)
        console.log(attributes,pickPrimitive.id % 9);
       attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromCssColorString(colors[pickPrimitive.id % 9]).withAlpha(0.3))
      }
      // 图元高亮
      pickPrimitive = pick
      let attributes = pickPrimitive.primitive.getGeometryInstanceAttributes(pick.id)
      console.log(attributes,'getGeometryInstanceAttributes');
      attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW.withAlpha(0.8))
      const res = await getOneHouseInfo({ id: pick.id })
      if (res.code == 200) {
        bubble && bubble.windowClose()
        // 加载弹窗进行可视化渲染
        bubble = new Bubble({
          viewer,
          position,
          houseInfo: res.data
        })
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

onMounted(() => {
  // 获取地图变量
  viewer = global.$viewer
  // 初始化数据
  initData()
  initHandler()

})

// 销毁组件时，同时清除地图影响
onUnmounted(() => {
  // 清除之前的高亮户
  heightList.length &&
    heightList.forEach((item) => {
      viewer.scene.primitives.remove(item)
    })
  heightList = []
  // 清除弹窗
  bubble && bubble.windowClose()
})
</script>
<style lang="scss">
.house {
  width: 30%;
  position: absolute;
  top: 4%;
  left: 4%;
  z-index: 999;
}
</style>
